package com.example.myproject.service.serviceImpl;

import com.example.myproject.model.Contract;
import com.example.myproject.model.ContractAssignment;
import com.example.myproject.model.User;
import com.example.myproject.repository.ContractAssignmentRepository;
import com.example.myproject.repository.ContractRepository;
import com.example.myproject.repository.UserRepository;
import com.example.myproject.service.ContractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class ContractServiceImpl implements ContractService {
    private static final Logger log = LoggerFactory.getLogger(ContractServiceImpl.class);

    @Autowired
    private ContractRepository contractRepository;
    @Autowired
    private ContractAssignmentRepository contractAssignmentRepository;
    @Autowired
    private UserRepository userRepository;



    // 获取所有合同
    @Override
    public List<Contract> getAllContracts() {
        log.debug("获取所有合同");
        return contractRepository.findAll();
    }

    @Override
    public Long getContractIdByName(String contractName) {
        Contract contract = contractRepository.findByName(contractName);
        if (contract != null) {
            log.debug("找到合同：{}，合同ID为：{}", contractName, contract.getId());
            return contract.getId();
        } else {
            log.debug("未找到合同名称为：{} 的合同", contractName);
            return 0L;
        }
    }

    // 根据合同名称和指定状态搜索合同
    @Override
    public List<Contract> searchContractsByNameAndStatus(String name, int status) {
        log.debug("根据名称：{} 和状态：{} 搜索合同", name, status);
        return contractRepository.findByNameContainingAndStatus(name, status);
    }

    // 根据名称搜索合同
    @Override
    public List<Contract> searchContractsByName(String name) {
        log.debug("根据名称搜索合同：{}", name);
        return contractRepository.findBynameContaining(name);
    }

    // 删除合同
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteContract(String name) {
        log.debug("尝试删除合同，合同名称：{}", name);
        contractRepository.deleteByName(name);
        log.debug("删除合同名称为：{} 的合同", name);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Contract draft(Contract contract, String username) {
        log.debug("用户 {} 开始起草合同, 合同详情: {}", username, contract);
        contract.setStatus(10); // 设置状态为待分配
        Contract savedContract = contractRepository.save(contract);
        log.debug("合同起草成功, 合同ID: {}", savedContract.getId());

        // 自动分配定稿权限
        if (savedContract != null && savedContract.getId() != null) {
            log.debug("自动分配定稿权限给用户 {}, 合同ID: {}", username, savedContract.getId());
            assignFinalizeRole(savedContract.getId(), username);
        } else {
            log.error("合同保存失败, 无法为用户 {} 分配定稿权限", username);
        }
        return savedContract;
    }

    private void assignFinalizeRole(Long contractId, String username) {
        User user = userRepository.findByUsername(username);
        if (user != null) {
            ContractAssignment assignment = new ContractAssignment();
            assignment.setContractId(contractId);
            assignment.setUserId(user.getId());
            assignment.setRole("Finalize");
            contractAssignmentRepository.save(assignment);
            log.debug("定稿权限分配成功: 用户ID {} -> 合同ID {} -> 角色 {}", user.getId(), contractId, "Finalize");
        } else {
            log.warn("未找到用户名为 {} 的用户, 无法分配定稿权限", username);
        }
    }


    // 更新会签意见
    @Override
    @Transactional
    public Contract updateCounterSignOpinion(String contractName, String opinion) {
        log.debug("更新合同：{} 的会签意见", contractName);
        Optional<Contract> contractOptional = Optional.ofNullable(contractRepository.findByName(contractName));
        return contractOptional.map(contract -> {
            contract.setStatus(3);
            contract.setCountersignOpinion(opinion);
            return contractRepository.save(contract);
        }).orElse(null);
    }

    // 更新审批意见
    @Override
    @Transactional
    public Contract updateApprovalOpinion(String contractName, String opinion, String status) {
        log.debug("更新合同：{} 的审批意见", contractName);
        Optional<Contract> contractOptional = Optional.ofNullable(contractRepository.findByName(contractName));
        return contractOptional.map(contract -> {
            contract.setStatus(Integer.parseInt(status));  // 假设 status 是一个整数值的字符串，表示合同状态
            contract.setApprovalOpinion(opinion);
            return contractRepository.save(contract);
        }).orElse(null);
    }

    // 更新签订意见
    @Override
    @Transactional
    public Contract updateSignOpinion(String contractName, String signInfo) {
        log.debug("更新合同：{} 的签订意见", contractName);
        Optional<Contract> contractOptional = Optional.ofNullable(contractRepository.findByName(contractName));
        return contractOptional.map(contract -> {
            contract.setStatus(8);  // 假设 8 表示合同签订完成状态
            contract.setSignOpinion(signInfo);
            return contractRepository.save(contract);
        }).orElse(null);
    }



    // 处理合同定稿
    @Override
    @Transactional
    public Contract finalizeContract(String contractName, String content) {
        log.debug("定稿合同：{}", contractName);
        Optional<Contract> contractOptional = Optional.ofNullable(contractRepository.findByName(contractName));
        return contractOptional.map(contract -> {
            contract.setContent(content);
            contract.setStatus(5); // 设置状态为已定稿
            return contractRepository.save(contract);
        }).orElse(null);
    }

    // 处理合同审批
    @Override
    public Contract approveContract(String contractName, String opinion, String status) {
        log.debug("审批合同：{}，审批意见：{}", contractName, opinion);
        Optional<Contract> contractOptional = Optional.ofNullable(contractRepository.findByName(contractName));
        return contractOptional.map(contract -> {
            contract.setContent(opinion);
            contract.setStatus("approved".equals(status) ? 7 : 0);
            log.debug("审批完成，合同状态已更新");
            return contractRepository.save(contract);
        }).orElse(null);
    }


    // 签订合同
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Contract signContract(String contractName, String signInfo) {
        log.debug("签订合同：{}", contractName);
        Optional<Contract> contractOptional = Optional.ofNullable(contractRepository.findByName(contractName));
        return contractOptional.map(contract -> {
            contract.setStatus(8); // 更新状态为已签订
            log.debug("签订完成，合同状态已更新");
            return contractRepository.save(contract);
        }).orElse(null);
    }

    //获取合同详细信息
    @Override
    public Optional<Contract> getContractDetailsByName(String contractName) {
        log.debug("获取合同详细信息：{}", contractName);
        return Optional.ofNullable(contractRepository.findByName(contractName));
    }

    // 获取指定状态的合同
    @Override
    public List<Contract> findContractsByStatus(int status) {
        log.debug("获取状态为：{} 的所有合同", status);
        return contractRepository.findByStatus(status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignContract(Long contractId, List<Long> countersignUserIds, List<Long> approvalUserIds, List<Long> signingUserAs) {
        log.debug("分配合同任务，合同ID：{}", contractId);

        Optional<Contract> contractOptional = contractRepository.findById(contractId);
        if (!contractOptional.isPresent()) {
            log.debug("未找到合同ID为 {} 的合同，分配任务失败", contractId);
            return false;
        }

        Contract contract = contractOptional.get();

        // 删除现有的任务分配
        contractAssignmentRepository.deleteByContractId(contractId);
        log.debug("已删除合同ID为 {} 的所有任务分配", contractId);

        // 分配会签任务
        countersignUserIds.forEach(userId -> {
            ContractAssignment assignment = new ContractAssignment();
            assignment.setContractId(contractId);
            assignment.setUserId(userId);
            assignment.setRole("Countersign");
            contractAssignmentRepository.save(assignment);
            log.debug("为合同ID {} 分配会签任务给用户ID {}", contractId, userId);
        });

        // 分配审批任务
        approvalUserIds.forEach(userId -> {
            ContractAssignment assignment = new ContractAssignment();
            assignment.setContractId(contractId);
            assignment.setUserId(userId);
            assignment.setRole("Approval");
            contract: contractAssignmentRepository.save(assignment);
            log.debug("为合同ID {} 分配审批任务给用户ID {}", contractId, userId);
        });

        // 分配签订任务
        signingUserAs.forEach(userId -> {
            ContractAssignment assignment = new ContractAssignment();
            assignment.setContractId(contractId);
            assignment.setUserId(userId);
            assignment.setRole("Signing");
            contractAssignmentRepository.save(assignment);
            log.debug("为合同ID {} 分配签订任务给用户ID {}", contractId, userId);
        });

        // 更新合同状态为1（待会签状态）
        contract.setStatus(1);
        contractRepository.save(contract);
        log.debug("合同状态更新为待会签状态，合同ID：{}", contractId);

        log.debug("所有任务分配完比，合同ID：{}", contractId);
        return true;
    }



    @Override
    @Transactional
    public Contract save(Contract contract) {
        log.debug("保存合同");
        return contractRepository.save(contract);
    }


    private void assignUsers(Contract contract, List<Long> userIds, String role) {
        for (Long userId : userIds) {
            log.debug("为合同ID {} 分配用户ID {} 到角色 {}", contract.getId(), userId, role);
            ContractAssignment assignment = new ContractAssignment();
            assignment.setContractId(contract.getId());
            assignment.setUserId(userId);
            assignment.setRole(role);
            contractAssignmentRepository.save(assignment);
            log.debug("用户ID {} 已被成功分配到合同ID {} 的 {} 角色。", userId, contract.getId(), role);
        }
        // Update contract status to 1
        contract.setStatus(1);
        contractRepository.save(contract);
    }

    @Override
    public void assignContractByName(String contractName, List<Long> countersignUserIds, List<Long> approvalUserIds, List<Long> signingUserIds) {
        log.debug("开始根据合同名称分配合同，合同名称：{}", contractName);
        Contract contract = contractRepository.findByName(contractName);
        if (contract == null) {
            log.debug("未找到合同名称为 '{}' 的合同。", contractName);
            return;
        }

        log.debug("合同名称 '{}' 对应的合同ID为 {}，开始分配用户角色。", contractName, contract.getId());
        assignUsers(contract, countersignUserIds, "countersign");
        assignUsers(contract, approvalUserIds, "approval");
        assignUsers(contract, signingUserIds, "signing");
        log.debug("合同名称 '{}' 的用户分配完成。", contractName);
    }


}
